package com.boomsecret.juc.tools;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author wangjinliang on 2019/1/23.
 */
public class CyclicBarrierDemo {
    private final static int THREAD_COUNT = 4;

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(THREAD_COUNT, () -> {
            System.out.println("thread start.");
        });

        Thread[] threads = new Thread[THREAD_COUNT];
        for (int index = 0; index < THREAD_COUNT; index ++) {
            threads[index] = new Thread(() -> {
                try {
                    cyclicBarrier.await();
                    System.out.println("threadId ----> " + Thread.currentThread().getId());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
            threads[index].start();
        }

        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("main end.");
    }
}
